<?php

namespace admin\index\controller;

use cmf\controller\AdminBaseController;
use think\Db;
use common\platform\model\AdminMenuModel;

/**
 * 后台管理中心框架首页
 * 
 * @author chenliming <19536238@qq.com>
 * @since     2018-05-05
 * 
 */
class IndexController extends AdminBaseController
{

    public function _initialize()
    {
        
        // 从系统配置中,DB中的.取相关数据
        $adminSettings = cmf_get_option('admin_settings');
      
        // 如果设置了登录密码,就需要在后面加上密码,否则无法访问.  
        if (empty($adminSettings['admin_password']) || $this->request->path() == config('default_root').'/'.$adminSettings['admin_password']) {
            $adminId = cmf_get_current_admin_id();
            if (empty($adminId)) {
                session("__LOGIN_BY_CMF_ADMIN_PW__", 1);//设置后台登录加密码
            }
        }
        
        parent::_initialize();
    }

    /**
     * 后台首页
     */
    public function index()
    {     
        $content = hook_one('admin_index_index_view');
        if (!empty($content)) {
            return $content;
        }
        // 每个人的菜单都是不同的,缓存减少访问
        $adminMenuModel = new AdminMenuModel();
        $menus          = cache('admin_menus_' . cmf_get_current_admin_id(), '', null, 'admin_menus');
//$menus=[];
        if (empty($menus)) {
            $menus = $adminMenuModel->menuTree();

            cache('admin_menus_' . cmf_get_current_admin_id(), $menus, null, 'admin_menus');
        }
      
        $this->assign("menus", $menus);
 
        $result = Db::name('AdminMenu')->order(["app" => "ASC", "controller" => "ASC", "action" => "ASC"])->select();
        $menusTmp = array();
        foreach ($result as $item){
            //去掉/ _ 全部小写。作为索引。
            $indexTmp = $item['app'].$item['controller'].$item['action'];
            $indexTmp = preg_replace("/[\\/|_]/","",$indexTmp);
            $indexTmp = strtolower($indexTmp);
            $menusTmp[$indexTmp] = $item;
        }
        $this->assign("menus_js_var",json_encode($menusTmp));
        

        //$admin = Db::name("user")->where('id', cmf_get_current_admin_id())->find();
        //$this->assign('admin', $admin);
        return $this->fetch(':index');
    }
}
